package com.wn.network.interceptor

import com.blankj.utilcode.util.LogUtils
import com.wn.network.constant.*
import com.wn.network.utils.CookiesManager
import okhttp3.Interceptor
import okhttp3.Response
import javax.inject.Inject
import javax.inject.Singleton

/**
 * @Author: wn
 * @Date: 2024/7/31 16:26
 * @Description: 头信息拦截器 --> 添加头信息( Cookie , Content-type )
 */
@Singleton
class HeaderInterceptor @Inject constructor(private val cookiesManager: CookiesManager) :
  Interceptor {
  override fun intercept(chain: Interceptor.Chain): Response {
    val request = chain.request()
    val newBuilder = request.newBuilder()
    newBuilder.addHeader("Content-type", "application/json; charset=utf-8")
    /**
     * URL                       host()
     * http://android.com/       "android.com"
     */
    val url = request.url.toString()
    val host = request.url.host

    // 不为空 且 包含这些接口中任意一个 添加 Cookies
    if (host.isNotEmpty() && (url.contains(COLLECTION_WEBSITE)
              || url.contains(NOT_COLLECTION_WEBSITE)
              || url.contains(ARTICLE_WEBSITE)
              || url.contains(COIN_WEBSITE))
    ) {
      val cookies = cookiesManager.getCookies()
      LogUtils.e("HeaderInterceptor:cookies:$cookies")
      if (!cookies.isNullOrEmpty()) {
        newBuilder.addHeader(KEY_COOKIE, cookies)
      }
    }
    return chain.proceed(newBuilder.build())
  }
}